package com.weixing.mall.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.weixing.mall.base.orm.MPage;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.enums.IsEnableEnum;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.api.model.enums.IsOfficialEnum;
import com.weixing.mall.provider.api.service.OrderServiceRpc;
import com.weixing.mall.provider.mapper.UpgradeMsgMapper;
import com.weixing.mall.provider.model.domain.Agent;
import com.weixing.mall.provider.model.domain.AgentRule;
import com.weixing.mall.provider.model.domain.UpgradeMsg;
import com.weixing.mall.provider.model.dto.UpgradeMsgDto;
import com.weixing.mall.provider.model.enums.AgentRuleStatusEnum;
import com.weixing.mall.provider.model.enums.IsReadEnum;
import com.weixing.mall.provider.model.vo.UpgradeMsgVo;
import com.weixing.mall.provider.service.IAgentRuleService;
import com.weixing.mall.provider.service.IAgentService;
import com.weixing.mall.provider.service.IUpgradeMsgService;
import com.weixing.mall.push.GtFwComponent;
import com.weixing.mall.push.PushMsg;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 代理商模块-代理商升级通知 服务实现类
 * </p>
 *
 * @author 0202
 * @since 2020-05-29
 */
@Service
public class UpgradeMsgServiceImpl extends ServiceImpl<UpgradeMsgMapper, UpgradeMsg> implements IUpgradeMsgService {
    @Autowired
    private IAgentService agentService;
    @Autowired
    private IAgentRuleService agentRuleService;
    @Autowired
    private OrderServiceRpc orderServiceRpc;
    @Autowired
    private UpgradeMsgMapper upgradeMsgMapper;
    @Autowired
    private GtFwComponent gtFwComponent;

    @Override
    public IPage<UpgradeMsgVo> selectListByCustomerId(MPage page, Long id, Integer isRead) {
        IPage<UpgradeMsgVo> pageList = upgradeMsgMapper.selectListByCustomerId(page, id, isRead);
        if (pageList.getRecords() != null && pageList.getRecords().size() > 0) {
            updateIsReadStatus(pageList.getRecords());
        }
        return pageList;
    }

    private void updateIsReadStatus(List<UpgradeMsgVo> volist) {
        List<UpgradeMsg> list = Lists.newArrayList();
        volist.forEach(umv -> {
            UpgradeMsg um = new UpgradeMsg();
            um.setId(umv.getId());
            um.setStatus(IsReadEnum.YES.getValue());
            list.add(um);
        });
        updateBatchById(list);
    }

    @Override
    public void addUpgradeMsg(UpgradeMsgDto upgradeMsgDto) {
        if (ObjectUtil.isNotEmpty(upgradeMsgDto)) {
            UpgradeMsg upgradeMsg = new UpgradeMsg();
            BeanUtils.copyProperties(upgradeMsgDto, upgradeMsg);
            upgradeMsg.setStatus(IsReadEnum.NO.getValue());
            save(upgradeMsg);
        }
    }

    @Override
    public void upgradeMsgTask() {
        List<String> cids =  agentService.loadKefuMasterCid();
        //查询所有可用代理商
        List<Agent> agentList = agentService.list(new LambdaQueryWrapper<Agent>()
                .eq(Agent::getIsEnable, IsEnableEnum.ENABLE.getValue())//启用的
                .eq(Agent::getIsOfficial, IsOfficialEnum.FORMAL.getValue()));//正式的
        if (agentList != null && agentList.size() > 0) {
            //通知消息收集
            List<UpgradeMsg> upgradeMsgList = Lists.newArrayList();
            for (Agent a : agentList) {
                //查询对应代理商晋升等级 这里需注意由于业务关系 金级银级不跨级晋升 并且默认等级是一级一级晋升不跨级
                if (a.getAgentLevel() == null || a.getAgentType() == null) {
                    continue;
                }
                AgentRule agentRule = agentRuleService.getOne(new LambdaQueryWrapper<AgentRule>()
                        .eq(AgentRule::getAgentLevel, a.getAgentLevel() - 1)//晋升等级
                        .eq(AgentRule::getAgentType, a.getAgentType())//等级类型
                        .eq(AgentRule::getRuleStatus, AgentRuleStatusEnum.STATUS1.getValue())//已发布
                        .last("LIMIT 1"));//多条默认取一条
                if (ObjectUtil.isEmpty(agentRule)) {
                    continue;
                }
                //判断是否符合晋升条件
                String endTime = DateTime.now().toString();
                String startTime = DateUtil.offsetMonth(DateTime.now(), -agentRule.getTimeCondition()).toString();
                Result result = orderServiceRpc.getAgentRuleData(a.getId(), startTime, endTime);
                if (!result.isSuccess() || result.getData() == null) {
                    continue;
                }
                Map<String, Object> map = (Map<String, Object>) result.getData();
                //业绩
                BigDecimal saleAmount = new BigDecimal(map.get("saleAmount").toString());
                //销量
                Integer saleNum = Integer.valueOf(map.get("saleNum").toString());
                //校验是否满足晋升条件
                if (saleAmount.intValue() >= agentRule.getAchievement() && saleNum >= agentRule.getSaleQuantity()) {
                    //满足添加通知消息
                    AgentLevelEnum levelEnum = EnumUtil.getIEnum(AgentLevelEnum.class, a.getAgentLevel());
                    String msg = a.getCustomerName() + "下面的" + levelEnum.getDesp() + "级代理满足晋升条件，请及时处理";
                    PushMsg pushMsg = new PushMsg();
                    pushMsg.setTitle("代理晋升提醒");
                    pushMsg.setBody(msg);
                    pushMsg.setClick_type("none");
                    if (CollUtil.isNotEmpty(cids)){
                        for (String cid : cids){
                            gtFwComponent.pushToSingleCid(pushMsg,cid);
                        }
                    }

                    UpgradeMsg um = new UpgradeMsg();
                    um.setAgentId(a.getId())
                            .setAgentName(a.getAgentName())
                            .setMobile(a.getMobile())
                            .setCustomerId(a.getCustomerId())
                            .setStatus(IsReadEnum.NO.getValue())
                            .setRemark(msg);
                    upgradeMsgList.add(um);
                }
            }
            if (upgradeMsgList != null && upgradeMsgList.size() > 0) {
                saveBatch(upgradeMsgList);
            }
        }
    }

}
